package com.athena.framework.url.websocket;

import com.athena.config.DefaultAppConfig;
import com.athena.framework.annotation.AnnotationParsing;
import org.glassfish.tyrus.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.DeploymentException;
import javax.websocket.server.ServerEndpoint;
import java.util.Set;

/**
 * 用于启动wensocket服务
 */
public class WebSocket implements AnnotationParsing {

    private final static Logger logger = LoggerFactory.getLogger(WebSocket.class);

    /**
     * 启动websocket服务
     */
    public void start() {
        if (logger.isInfoEnabled()) {
            logger.info("开始启动WebSocket。。。");
        }
        //获取websocket的消息处理类
        Set<Class<?>> classSet = findAllScanPackgeByAnnotation(ServerEndpoint.class);
        if (classSet != null && classSet.size() > 0) {
            //启动websocket
            Server server = new Server(DefaultAppConfig.webSocketHostName, DefaultAppConfig.webSocketPort, "/",
                    null, classSet);
            try {
                server.start();
                if (logger.isInfoEnabled()) {
                    logger.info("WebSocket启动完成: ws://" + DefaultAppConfig.webSocketHostName + ":" + DefaultAppConfig.webSocketPort);
                }
            } catch (DeploymentException e) {
                String msg = "WebSocket启动失败！\r\n" + e.getMessage();
                logger.error(msg);
                throw new RuntimeException(msg);
            }
        } else {
            if (logger.isInfoEnabled()) {
                logger.info("没有找到websocket消息处理类，不启动websocket服务。");
            }
        }
    }

    @Override
    public void parsing() {

    }
}
